/*
首先新建在TIMBASURVEYS__SurveyResponse__c新建一个字符串类型字段isCollectedRes，用来表示同一个店面同一个问卷是否收集过答卷。
PDA操作时这个字段的值为字符串的'True' and 'False'，web端操作是为空字符串。
 trigger将读取PDA提交的Respone记录做下面的逻辑处理:
 1.对于trigger里面可以获取本次问卷卷的所有答案，同一个店面同一个Survey(isCollectedRes为true)的答案答案记录才去更新TIMBASURVEYS__Survey__c 的
   TIMBASURVEYS__CollectedResponses__c（累加）、TIMBASURVEYS__CollectingData__c 、TIMBASURVEYS__Status__c。
   TIMBASURVEYS__Recipient__c 的 TIMBASURVEYS__Collected__c。
 2. 赋值TIMBASURVEYS__Survey_Summary__c中TIMBASURVEYS__Complete_Survey_Name__c、
     TIMBASURVEYS__Recipient__c、TIMBASURVEYS__Survey__c,NAME 4个字段。其中NAME字段格式如下：
     PDA Submit-(TSR:TEST TSR;ClientName:Iss测试门店2)，即是PDA Submit（Role：Name;ClientName：店面名称）。
 3. 赋值TIMBASURVEYS__Question_Summary__c的 TIMBASURVEYS__Answer__c、TIMBASURVEYS__Question__c、
     TIMBASURVEYS__Survey_Summary__c，NAME 4个字段。
 4. 赋值TIMBASURVEYS__QuestionType__c（SurveyStats） 中TIMBASURVEYS__AnswerOption__c、TIMBASURVEYS__SurveyQuestion__c、
     TIMBASURVEYS__TimesSelected__c。其中 TIMBASURVEYS__TimesSelected__c是同一个问题相同答案出现次数的统计。

huang xiaojiang 20101102  create
huang xiaojiang 20110414 modified 对答案是否收集过重新判断 
   
 由于需要获取很多关联objcet字段信息，特别是更新Survey时，所以把trigger做成after insert
 huangxiaojiang 20101103       
*/

trigger ChangeByPDA on TIMBASURVEYS__SurveyResponse__c (after insert)
 {
   if(trigger.new.size()>0)
   {
     list<TIMBASURVEYS__SurveyResponse__c> lstTriggerNew=new list<TIMBASURVEYS__SurveyResponse__c>();
     for(TIMBASURVEYS__SurveyResponse__c res:trigger.new){
         if(res.isCollectedRes__c!=null){//收集PDA提交上来的记录
             lstTriggerNew.add(res);
         }
     }
     
     if(lstTriggerNew.size()>0){
        string strFlagNotOptionType='Option';//非选项型答案标识
         
         set<id> sResId=new set<id>();//存放当前问题答案id
         Set<id> setRec=new Set<id>();//存放需要更新Recipient__c的id
         set<id> setQues=new set<id>();//存放问题id
         //用于判断是否需要处理questionType，同一个店面同一个问卷（相同的recipient）同一个答案选项需不需要处理
         set<string> setIsOperQT=new set<string>();
         map<string,TIMBASURVEYS__SurveyResponse__c> MapIsReduceQT=new map<string,TIMBASURVEYS__SurveyResponse__c>();//用于判断questionType是是否要减一
         TIMBASURVEYS__Recipient__c oRecipient=null;
         
         list<TIMBASURVEYS__Survey_Summary__c> lstSurveySum=new  list<TIMBASURVEYS__Survey_Summary__c>();
         TIMBASURVEYS__Survey_Summary__c oSummary=null;
         list<TIMBASURVEYS__Question_Summary__c> lstSurveyQuesSum=new  list<TIMBASURVEYS__Question_Summary__c>();
         TIMBASURVEYS__Question_Summary__c oQuesSum=null;
         
         TIMBASURVEYS__QuestionType__c oQuesType=null;
         set<id> setAnswOppId=new  set<id>();  
         set<id> setSurveyId=new set<id>();
         string strKey5='';
         string strKey6='';
         string strKey7='';//判断同一个是否收集过问卷
         set<string> setSurveyIsRes=new set<string>();
         
         for(TIMBASURVEYS__SurveyResponse__c res:lstTriggerNew)
         {
           
           sResId.add(res.id);
           //获取对应的AnswerOpptionId
            setAnswOppId.add(res.TIMBASURVEYS__AnswerOption__c);
           
           //获取对应的SurveyId 15位id
            setSurveyId.add(res.SurveyId__c);
           
           //获取对应的RecipientId
            setRec.add(res.TIMBASURVEYS__Recipient__c);
            
            //获取对应的questionid
            setQues.add(res.TIMBASURVEYS__SURVEYQUESTION__C);
    
         }
         
         if(setSurveyId.size()>0){
             //查询当前相关的所有答案，排除当前trigger产生的记录
             list<TIMBASURVEYS__SurveyResponse__c> lResAll=[select id,SurveyId__c,TIMBASURVEYS__Recipient__c,TIMBASURVEYS__AnswerOption__c,TIMBASURVEYS__SurveyQuestion__c
              from TIMBASURVEYS__SurveyResponse__c where id not in:sResId  and TIMBASURVEYS__Recipient__c in:setRec and TIMBASURVEYS__Recipient__c!=null]; 
            if(lResAll.size()>0){
                for(TIMBASURVEYS__SurveyResponse__c res:lResAll){        
                    //获取需要操作questionType的主键
                    strKey5=string.valueOf(res.TIMBASURVEYS__Recipient__c)+string.valueOf(res.TIMBASURVEYS__AnswerOption__c);
                    setIsOperQT.add(strKey5);
                    strKey6=string.valueOf(res.TIMBASURVEYS__Recipient__c)+string.valueOf(res.TIMBASURVEYS__SurveyQuestion__c);
                    MapIsReduceQT.put(strKey6,res);
                    strKey7=string.valueOf(res.TIMBASURVEYS__Recipient__c)+string.valueOf(res.SurveyId__c);
                    setSurveyIsRes.add(strKey7);
                            
                }
            }     
             
            //查询question
            map<id,TIMBASURVEYS__SurveyQuestion__c> mapQuestion=new map<id,TIMBASURVEYS__SurveyQuestion__c>(
               ( list<TIMBASURVEYS__SurveyQuestion__c>)[select id,name,TIMBASURVEYS__ROWPLACEMENT__C from TIMBASURVEYS__SurveyQuestion__c
                   where id in:setQues]);
               
            //查询QuestionType__c,同一个问题的同一个答案选项只有一条记录     
            list<TIMBASURVEYS__QuestionType__c> lstQTypeTemp=[select id,TIMBASURVEYS__AnswerOption__c,TIMBASURVEYS__SurveyQuestion__c,TIMBASURVEYS__TimesSelected__c 
              ,TIMBASURVEYS__Survey__c from TIMBASURVEYS__QuestionType__c where TIMBASURVEYS__SurveyQuestion__c in: setQues
               and TIMBASURVEYS__SurveyQuestion__c!=null];  
              
            Map<string,TIMBASURVEYS__QuestionType__c> mapQuesType=new  Map<string,TIMBASURVEYS__QuestionType__c>();
            //Map<string,TIMBASURVEYS__QuestionType__c> mapQuesTypeRed=new  Map<string,TIMBASURVEYS__QuestionType__c>();
            string strKey2='';
            for(TIMBASURVEYS__QuestionType__c qt:lstQTypeTemp)
            {
                 strKey2=string.valueOf(qt.TIMBASURVEYS__AnswerOption__c);
                 mapQuesType.put(strKey2,qt);//一个question的AnswerOption__c对应唯一条QuestionType记录
                 //mapQuesTypeRed.put(qt.TIMBASURVEYS__SurveyQuestion__c,qt);
            }
            lstQTypeTemp.clear();
            //存放新增QuestionType
            map<string,TIMBASURVEYS__QuestionType__c> mapInsertQuestionType=new map<string,TIMBASURVEYS__QuestionType__c>();   
            
            //查询对应的Survey      
            TIMBASURVEYS__Survey__c oSurvey=null;
            Map<id,TIMBASURVEYS__Survey__c> mapSurvey=new Map<id,TIMBASURVEYS__Survey__c>((list<TIMBASURVEYS__Survey__c>)
                 [select id,Name,TIMBASURVEYS__CollectedResponses__c,TIMBASURVEYS__CollectingData__c,TIMBASURVEYS__Status__c from TIMBASURVEYS__Survey__c
                 where id in:setSurveyId]);   
            Map<id,Boolean> mapIsAdd=new Map<id,Boolean>();//判断一个问卷是否已经累加过
            for(TIMBASURVEYS__Survey__c s:mapSurvey.values()){
                mapIsAdd.put(s.id,false);
            }
             
             //查询surveySummary
             set<id> setSurSumy=new set<id>();
             list<TIMBASURVEYS__Survey_Summary__c> lSurveySumyTemp=[select id,TIMBASURVEYS__Recipient__c,TIMBASURVEYS__Survey__c
                 from TIMBASURVEYS__Survey_Summary__c where TIMBASURVEYS__Recipient__c in:setRec and TIMBASURVEYS__Recipient__c!=null];
             string strKey3='';
             map<string,TIMBASURVEYS__Survey_Summary__c> mapSurSumy=new  map<string,TIMBASURVEYS__Survey_Summary__c>();
             for(TIMBASURVEYS__Survey_Summary__c ss:lSurveySumyTemp){
                 strKey3=string.valueOf(ss.TIMBASURVEYS__Recipient__c);
                 mapSurSumy.put(strKey3,ss);
                 setSurSumy.add(ss.id);//获取surveySummarId
             }    
             
             //查询questionSummary
             list<TIMBASURVEYS__Question_Summary__c > lQuesSumr=[select id,SurveyId__c,Recipient__c,TIMBASURVEYS__Question__c 
                 from TIMBASURVEYS__Question_Summary__c where TIMBASURVEYS__Survey_Summary__c in:setSurSumy and TIMBASURVEYS__Survey_Summary__c!=null];     
             map<string,TIMBASURVEYS__Question_Summary__c> mapQuesSumr=new   map<string,TIMBASURVEYS__Question_Summary__c>();
            string strKey4='';
             for(TIMBASURVEYS__Question_Summary__c qs:lQuesSumr){
                 strKey4=string.valueOf(qs.Recipient__c)+string.valueOf(qs.TIMBASURVEYS__Question__c);
                 mapQuesSumr.put(strKey4,qs);
             }
             list<TIMBASURVEYS__Question_Summary__c > lDeleteQuesSumr=new list<TIMBASURVEYS__Question_Summary__c >();//需要删除的qs列表
             
             //本次答案对应的问卷Id
             string strSurId='';
             string strRoleName=[select name from Profile  where id=:userInfo.getProfileId() limit 1 ].Name;
             string strUserName=userInfo.getName();
             string ouletName='';
             
             for(TIMBASURVEYS__SurveyResponse__c surRes:lstTriggerNew)
             {
                
                //更新问卷响应数
                strKey7=string.valueOf(surRes.TIMBASURVEYS__Recipient__c)+string.valueOf(surRes.SurveyId__c);
                if(!setSurveyIsRes.contains(strKey7)){
                    oSurvey=mapSurvey.get(surRes.SurveyId__c);
                    if(!oSurvey.TIMBASURVEYS__CollectingData__c){
                        oSurvey.TIMBASURVEYS__CollectingData__c=true;
                        oSurvey.TIMBASURVEYS__CollectedResponses__c=1;
                        oSurvey.TIMBASURVEYS__Status__c='Open';
                        
                    }else{
                        if(!mapIsAdd.get(surRes.SurveyId__c)){//一个survey很多答卷只更新一个响应,当false时才更新
                            oSurvey.TIMBASURVEYS__CollectedResponses__c=oSurvey.TIMBASURVEYS__CollectedResponses__c+1;
                            mapIsAdd.put(surRes.SurveyId__c,true);             
                        }
                        
                    }
                }
                           
                //处理surveySummary
                strKey3=string.valueOf(surRes.TIMBASURVEYS__Recipient__c);
                 //同一个recipient只增加一条记录
                if(!mapSurSumy.containsKey(strKey3)){
                    oSummary=new TIMBASURVEYS__Survey_Summary__c();
                    oSummary.TIMBASURVEYS__Recipient__c=surRes.TIMBASURVEYS__Recipient__c;
                    oSummary.TIMBASURVEYS__Survey__c=mapSurvey.get(surRes.SurveyId__c).id;
                    oSummary.TIMBASURVEYS__Complete_Survey_Name__c=mapSurvey.get(surRes.SurveyId__c).Name;
                    //格式：PDA Submit（Role：Name;outletName：店面名称）
                    ouletName=surRes.OutletName__c;
                    string strResult='PDA Submit（'+strRoleName+':'+strUserName+';outletName：'+ouletName+')';
                    if(strResult.length()>80)
                    {
                       strResult=strResult.substring(0,79);
                    }
                    oSummary.NAME=strResult;
                   
                    lstSurveySum.add(oSummary);
                                     
                }
                
        
                //处理QuestionType，TIMBASURVEYS__TimesSelected__c是累加
                strKey2=string.valueOf(surRes.TIMBASURVEYS__AnswerOption__c);
                strKey5=string.valueOf(surRes.TIMBASURVEYS__Recipient__c)+string.valueOf(surRes.TIMBASURVEYS__AnswerOption__c);
                strKey6=string.valueOf(surRes.TIMBASURVEYS__Recipient__c)+string.valueOf(surRes.TIMBASURVEYS__SurveyQuestion__c);
                if(!setIsOperQT.contains(strKey5))//如果同一个recipient这个答案选项不存在记录
                {
                   //其他recipient对这个答案选项进行回答，需要加1
                   if(mapQuesType.containsKey(strKey2)){
                       oQuesType=mapQuesType.get(strKey2);
                       oQuesType.TIMBASURVEYS__TimesSelected__c=oQuesType.TIMBASURVEYS__TimesSelected__c+1;//累加为1               
                   }else{
                       //如果这个recipient对相同问题的其他答案选项有回答过问题，把这个答案选项计数减1
                       if(MapIsReduceQT.containsKey(strKey6)){
                           oQuesType=new TIMBASURVEYS__QuestionType__c();              
                           oQuesType=mapQuesType.get(MapIsReduceQT.get(strKey6).TIMBASURVEYS__AnswerOption__c);
                           oQuesType.TIMBASURVEYS__TimesSelected__c=oQuesType.TIMBASURVEYS__TimesSelected__c-1;//减一
                           
                       }
                        oQuesType=new TIMBASURVEYS__QuestionType__c();
                        oQuesType.TIMBASURVEYS__AnswerOption__c=surRes.TIMBASURVEYS__AnswerOption__c;
                        oQuesType.TIMBASURVEYS__SurveyQuestion__c=surRes.TIMBASURVEYS__SurveyQuestion__c;
                        oQuesType.TIMBASURVEYS__Survey__c=surRes.SurveyId__c;
                        oQuesType.TIMBASURVEYS__TimesSelected__c=1;//第一次累加为1
                        //把新增的TIMBASURVEYS__QuestionType__c加入到map中
                        mapInsertQuestionType.put(strKey2,oQuesType);           
                   }
                }
                  
               } 
               
               
               //处理Recipient
               list<TIMBASURVEYS__Recipient__c> lstReci=[select id, TIMBASURVEYS__Collected__c from TIMBASURVEYS__Recipient__c
                    where id in:setRec]; 
               for(TIMBASURVEYS__Recipient__c rc:lstReci)
               {
                  rc.TIMBASURVEYS__Collected__c=true;
               }
        
              //更新recipient
              update lstReci;
              
              
              //处理survey
              
             //list<TIMBASURVEYS__Recipient__c> lRecipientResponse=new list<TIMBASURVEYS__Recipient__c>();
             //lRecipientResponse=[select id, TIMBASURVEYS__Collected__c,TIMBASURVEYS__Survey__c from TIMBASURVEYS__Recipient__c
                   //where TIMBASURVEYS__Collected__c=:true and TIMBASURVEYS__Survey__c in:setSurveyId and TIMBASURVEYS__Survey__c!=null
                     //and createdDate>:date.today().addmonths(-1) limit 1000];
             //先全部置0        
             //for(TIMBASURVEYS__Survey__c s:mapSurvey.values()){
                 //s.TIMBASURVEYS__CollectedResponses__c=0;
                 //s.TIMBASURVEYS__CollectingData__c=true;
                 //s.TIMBASURVEYS__Status__c='Open';
                 
             //}
             //for(TIMBASURVEYS__Recipient__c r:lRecipientResponse){
                 //if(mapSurvey.containsKey(r.TIMBASURVEYS__Survey__c)){
                     //oSurvey=mapSurvey.get(r.TIMBASURVEYS__Survey__c); 
                     //oSurvey.TIMBASURVEYS__CollectedResponses__c=oSurvey.TIMBASURVEYS__CollectedResponses__c+1;              
                 //}    
             //}
             update  mapSurvey.values();       
               
               //更新SurveySurmmary
               if(lstSurveySum.size()>0){ 
                   //SurveySurmmary
                   insert lstSurveySum;
                   for(TIMBASURVEYS__Survey_Summary__c ss:lstSurveySum){//把新增的SurveySummary加入map中
                     strKey3=string.valueOf(ss.TIMBASURVEYS__Recipient__c);
                     if(!mapSurSumy.containsKey(strKey3)){
                         mapSurSumy.put(strKey3,ss);   
                     }
                             
                   }           
             
               }
               
        
               //处理questionSummary需要surveySummary作为父id
               for(TIMBASURVEYS__SurveyResponse__c surRes:lstTriggerNew){         
                   strKey3=string.valueOf(surRes.TIMBASURVEYS__Recipient__c);
                   if(surRes.OPTIONVALUE__C!=strFlagNotOptionType){//如果是选项类型答案              
                       strKey4=string.valueOf(surRes.TIMBASURVEYS__RECIPIENT__C).substring(0,15)+mapQuestion.get

(surRes.TIMBASURVEYS__SURVEYQUESTION__C).name;
                       if(!mapQuesSumr.containsKey(strKey4)){//如果同一个店面同一个survey(同一个recipient)对同一个选项型问题已经回答过问题，先删除，再新增
                           
                           lDeleteQuesSumr.add(mapQuesSumr.get(strKey4));//添加要删除的记录
                           
                            //在QuestionSumarry新增一条记录
                            oQuesSum=new TIMBASURVEYS__Question_Summary__c();
                            oQuesSum.TIMBASURVEYS__Answer__c=surRes.TIMBASURVEYS__STRINGRESPONSE__C;
                            oQuesSum.TIMBASURVEYS__Question__c=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).name;
                            oQuesSum.NAME=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).name; 
                            oQuesSum.TIMBASURVEYS__POSITION__C=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).TIMBASURVEYS__ROWPLACEMENT__C;
                            oQuesSum.TIMBASURVEYS__Survey_Summary__c=mapSurSumy.get(strKey3).id;        
                            lstSurveyQuesSum.add(oQuesSum);  
                                      
                       }else{//新增这个选项型答案
                       
                            //在QuestionSumarry新增一条记录
                            oQuesSum=new TIMBASURVEYS__Question_Summary__c();
                            oQuesSum.TIMBASURVEYS__Answer__c=surRes.TIMBASURVEYS__STRINGRESPONSE__C;
                            oQuesSum.TIMBASURVEYS__Question__c=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).name;
                            oQuesSum.NAME=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).name;
                            oQuesSum.TIMBASURVEYS__POSITION__C=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).TIMBASURVEYS__ROWPLACEMENT__C;
                            oQuesSum.TIMBASURVEYS__Survey_Summary__c=mapSurSumy.get(strKey3).id;    
                            lstSurveyQuesSum.add(oQuesSum);                      
                       }    
                   }else{//其他类型如文本类型，直接新增
                            oQuesSum=new TIMBASURVEYS__Question_Summary__c();
                            oQuesSum.TIMBASURVEYS__Answer__c=surRes.TIMBASURVEYS__STRINGRESPONSE__C;
                            oQuesSum.TIMBASURVEYS__Question__c=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).name;
                            oQuesSum.NAME=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).name; 
                            oQuesSum.TIMBASURVEYS__POSITION__C=mapQuestion.get(surRes.TIMBASURVEYS__SurveyQuestion__c).TIMBASURVEYS__ROWPLACEMENT__C;
                            oQuesSum.TIMBASURVEYS__Survey_Summary__c=mapSurSumy.get(strKey3).id;  
                            lstSurveyQuesSum.add(oQuesSum);             
                   }       
               }
             
               
               //更新QuestionSummary 
               //if(lDeleteQuesSumr.size()>0){//先删除QuestionSummary 
                  //delete  lDeleteQuesSumr;
               //}             
               if(lstSurveyQuesSum.size()>0){
                    insert lstSurveyQuesSum;     
               }      
              
                    
               //update QuesType
               //if(mapQuesTypeRed.size()>0){
                   //update mapQuesTypeRed.values();
               //}
               if(mapQuesType.size()>0){
                    update mapQuesType.values();       
               }
               
               if(mapInsertQuestionType.size()>0){
                   insert mapInsertQuestionType.values();    
               }     
     }  
        
     }
     
  }  
 }